import collections
from random import choice

# 构建没有方法简单的类
Card = collections.namedtuple('Card', ['rank', 'suit'])


class FrenchDeck:
    ranks = [str(n) for n in range(2, 11)] + list('JQKA')
    suits = 'spades diamonds clubs hearts'.split()

    def __init__(self):
        self._cards = [Card(rank, suit) for suit in self.suits for rank in self.ranks]

    def __len__(self):
        """ 满足 len() 方法
            结合__getitem__()实现切片迭代
        """
        return len(self._cards)

    def __getitem__(self, position):
        """ FrenchDeck[x] 访问
            random.choice()方法
            从index 12 开始 每隔13取一个值 print(deck[12::13])
            可迭代
        """
        return self._cards[position]


suits_values = dict(spades=3, hearts=2, diamonds=1, clubs=0)


def spades_high(c):
    rank_value = FrenchDeck.ranks.index(c.rank)
    return rank_value * len(suits_values) + suits_values[c.suit]


if __name__ == '__main__':

    deck = FrenchDeck()
    print(len(deck))
    print(deck[0])
    print(choice(deck))
    print(deck[:3])
    # 从index 12 开始 每隔13取一个值
    print(deck[12::13])
    # 可迭代
    for c in reversed(deck):
        print(c)
    print(Card('Q', 'hearts') in deck)
    print(Card('7', 'beasts') in deck)
    for card in sorted(deck, key=spades_high):
        print(card)
